﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SQLite;
using System.Data;

namespace OpenMobileStoreModel
{
    public enum InvoiceType
    {
        SaleInvoice,
        RevisionInvoice,
        CheckInvoice
    }

    public class InvoiceFactory
    {
        public static SQLiteConnection Db
        {
            get
            {
                return Store.Instance.Db;
            }
        }

        public static Invoice New(InvoiceType aType)
        {
            Db.Open();
            using (Db)
            {
                SQLiteCommand cmd = new SQLiteCommand("INSERT INTO invoice (type) VALUES (@type);", Db);
                using (cmd)
                {
                    SQLiteParameter prmType = new SQLiteParameter("@type", DbType.Int64);
                    prmType.Value = (long)aType;
                    cmd.Parameters.Add(prmType);
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "SELECT * FROM invoice WHERE id=last_insert_rowid()";
                    SQLiteDataReader rdr = cmd.ExecuteReader();
                    rdr.Read();
                    return newInvoice(rdr);
                }
            }
        }

        public static Invoice GetById(long aId)
        {
            throw new System.NotImplementedException();
        }

        private static Invoice newInvoice(SQLiteDataReader rdr)
        {
            InvoiceType type = (InvoiceType) rdr.GetInt64(1);
            switch (type)
            {
                case InvoiceType.SaleInvoice:
                    return new SaleInvoice(rdr);
                case InvoiceType.RevisionInvoice:
                    return new RevisionInvoice(rdr);
                case InvoiceType.CheckInvoice:
                    return new CheckInvoice(rdr);
                default:
                    return new SaleInvoice(rdr);
            }
        }
    }
}
